package com.jiaanpei.frameproject.base;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SlidingPaneLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.jiaanpei.frameproject.R;
import com.jiaanpei.frameproject.app.AppApplication;
import com.jiaanpei.frameproject.app.Constants;
import com.jiaanpei.frameproject.manage.ActivityManager;
import com.jiaanpei.frameproject.modle.appupdate.AppUpdateManager;
import com.jiaanpei.frameproject.modle.appupdate.DownLoadObserver;
import com.jiaanpei.frameproject.modle.appupdate.DownloadInfo;
import com.jiaanpei.frameproject.modle.appupdate.DownloadManager;
import com.jiaanpei.frameproject.modle.appupdate.UpdateEvent;
import com.jiaanpei.frameproject.modle.bean.appupdate.AppUpdateBean;
import com.jiaanpei.frameproject.modle.bean.appupdate.AppUpdateRequestBean;
import com.jiaanpei.frameproject.modle.bean.base.BaseLoader;
import com.jiaanpei.frameproject.modle.bean.base.BaseRequest;
import com.jiaanpei.frameproject.modle.bean.base.BaseResponse;
import com.jiaanpei.frameproject.modle.bean.base.CallBackListener;
import com.jiaanpei.frameproject.utils.StatusBarUtil;
import com.jiaanpei.frameproject.utils.Utils;
import com.jiaanpei.frameproject.widget.MyAPPUpdateDialog;
import com.jiaanpei.frameproject.widget.MyProgressDialog;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity extends AppCompatActivity implements SlidingPaneLayout.PanelSlideListener {
    private Unbinder mUnBinder;
    protected BaseActivity mContext;
    protected PushAgent mPushAgent;
    private Toolbar mToolBar;
    private MyProgressDialog progressDialog;
    protected MyAPPUpdateDialog updateDialog;

    //app更新
    public static final int NM = 99;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(getLayout());
        EventBus.getDefault().register(this);
        mUnBinder = ButterKnife.bind(this);
        mContext = this;
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.onAppStart();
        // 每打开一个新页面都加栈里
        ActivityManager.getInstance().addActivity(this);
//        hideNavigationBar();//有的手机底部导航占位，暂不处理
        initEventAndData();
        initSwipeBackFinish();
        StatusBarUtil.initStatusBarConfig(this, mToolBar);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    protected abstract int getLayout();
    protected abstract void initEventAndData();
    public AppCompatActivity getContext() {
        return mContext;
    }
    @Override
    public void onPanelSlide(@NonNull View view, float v) {

    }

    @Override
    public void onPanelOpened(@NonNull View view) {
        finish();
        this.overridePendingTransition(0, R.anim.slide_out_right);
    }

    @Override
    public void onPanelClosed(@NonNull View view) {

    }
    protected void setToolBar(Toolbar toolbar, String title) {
        mToolBar = toolbar;
        toolbar.setTitle(title);
        toolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }
    /**
     * 初始化滑动返回
     */
    private void initSwipeBackFinish() {
        if (isSupportSwipeBack() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            SlidingPaneLayout slidingPaneLayout =  new SlidingPaneLayout(this);
            //通过反射改变mOverhangSize的值为0，这个mOverhangSize值为菜单到右边屏幕的最短距离，默认
            //是32dp，现在给它改成0
            try {
                //属性
                Field f_overHang = SlidingPaneLayout.class.getDeclaredField("mOverhangSize");
                f_overHang.setAccessible(true);
                f_overHang.set(slidingPaneLayout, 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            slidingPaneLayout.setPanelSlideListener(this);
            slidingPaneLayout.setSliderFadeColor(getResources().getColor(android.R.color.transparent));

            View leftView = new View(this);
            leftView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            slidingPaneLayout.addView(leftView, 0);

            ViewGroup decor = (ViewGroup) getWindow().getDecorView();
            ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
            decorChild.setBackgroundColor(getResources().getColor(android.R.color.white));
            decor.removeView(decorChild);
            decor.addView(slidingPaneLayout);
            slidingPaneLayout.addView(decorChild, 1);
        }
    }
    /**
     * 是否支持滑动返回
     *
     * @return
     */
    protected boolean isSupportSwipeBack() {
        return true;
    }

    /**
     * 启动loading
     */
    public void startLoading(String content) {
        if (progressDialog == null) {
            progressDialog = MyProgressDialog.createDialog(this, TextUtils.isEmpty(content) ? "loading...":content);
        }
        if(!isFinishing()&&!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }
    /**
     * 停止loading
     */
    public void stopLoading() {
        if (progressDialog != null&&progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    public void showAppUpdate(AppUpdateBean baseInfo) {

        if(updateDialog==null){
            updateDialog = new MyAPPUpdateDialog(ActivityManager.getInstance().currentActivity(),baseInfo);
        }
        if(!isFinishing()&&!updateDialog.isShowing()) {
            updateDialog.show();
        }

    }

    //动态申请权限
    public static  OnPermissionCallback callback;
    public static void requestPermission(String[] permissions, Activity context, OnPermissionCallback onPermissionCallback){
        if(context==null){
            return;
        }
        callback = onPermissionCallback;
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionsList = new ArrayList<>();
            for(String permission:permissions){
                if(ContextCompat.checkSelfPermission(context,permission)!= PackageManager.PERMISSION_GRANTED){
                    permissionsList.add(permission);
                }
            }
            if(!permissionsList.isEmpty()){
                ActivityCompat.requestPermissions(context,permissionsList.toArray(new String[permissionsList.size()]),1);
            }else {
                if(callback!=null){
                    callback.onGranted();
                }
            }
        }else{
            if(callback!=null){
                callback.onGranted();

            }
        }
    }
    @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults.length>0){
            List<String> deniedPermissions = new ArrayList<>();
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i]!=PackageManager.PERMISSION_GRANTED){
                    deniedPermissions.add(permissions[i]);
                }
            }
            if(deniedPermissions.isEmpty()){
                if(callback!=null){
                    callback.onGranted();

                }
            }else{
                if(callback!=null){
                    callback.onDenied(deniedPermissions);
                }
            }
        }
    }
    public interface OnPermissionCallback{
        void onGranted();
        void onDenied(List<String> deniedPermissions);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(UpdateEvent event) {
        boolean flag=Utils.lacksPermissions(this,new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE});
        if(!flag){
            if(!TextUtils.isEmpty(event.getUrl())&&updateDialog!=null){
                AppUpdateManager.getInstance().downMyApp(this,event.getUrl(),updateDialog);
            }
        }else{
            initUpdateReadnWrite(event.getUrl());
        }
    }

    protected void initUpdateReadnWrite(String url) {
        requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, getContext(), new BaseActivity.OnPermissionCallback() {
            @Override
            public void onGranted() {
                if(!TextUtils.isEmpty(url)&&updateDialog!=null){
                    AppUpdateManager.getInstance().downMyApp(BaseActivity.this,url,updateDialog);
                }else{
                    File file = new File( Constants.BASEPATH);
                    DownloadManager.getInstance(url).deleteFiles(file);
                }
            }

            @Override
            public void onDenied(List<String> deniedPermissions) {
            }
        });
    }



    public void getAppUpdateForNet() {

        AppUpdateRequestBean requestBean = new AppUpdateRequestBean();
//        requestBean.currentVersion=String.valueOf(Utils.getVersionCode(BaseActivity.this));
        BaseRequest baseRequest = new BaseRequest("60");
        baseRequest.setRequestBaseInfo(requestBean);
        BaseLoader.AppUpdateBean(baseRequest, new CallBackListener<AppUpdateBean>(this, true) {
            @Override
            protected void onSuccess(BaseResponse<AppUpdateBean> result) {
                BaseResponse.BaseResponseBody<AppUpdateBean> body = result.body;

                AppUpdateBean baseInfo = body.baseInfo;
                String errCode = result.head.errCode;
                String errMsg = result.head.errMsg;
                if(baseInfo!=null&&errCode.equals("000")){
                    String isUpdate = baseInfo.getIsUpdate();
                    if(!TextUtils.isEmpty(isUpdate)&&isUpdate.equals("1")){
                        showAppUpdate(baseInfo);
                    }else{
                        boolean flag= Utils.lacksPermissions(BaseActivity.this,new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE});
                        if(!flag){
                            File file = new File( Constants.BASEPATH);
                            DownloadManager.getInstance(baseInfo.getApkUrl()).deleteFiles(file);
                        }else{
                            initUpdateReadnWrite("");
                        }

                    }
                }

            }

            @Override
            protected void requestError(String error) {
                super.requestError(error);
            }
        });
    }
}
